package com.computerManagementSystem.interceptor;

import com.computerManagementSystem.mapper.MemberLoginMapper;
import com.computerManagementSystem.service.MemberServiceImpl;
import com.computerManagementSystem.util.CookieUtil;
import com.computerManagementSystem.util.JWTUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * @author 赖志宇
 * @date 2020/6/21 2:40
 */
public class MemberLoginInterceptor implements HandlerInterceptor {
    @Resource(name = "MemberService")
    private MemberServiceImpl memberService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = CookieUtil.getCookieValueNamedToken(request);
        if (request.getServletPath().equals("/member/login")) {
            if (request.getMethod().equals("POST"))
                return true;
            else if (JWTUtil.verifyToken(token)) {
                //getRole(response,request);
                response.sendRedirect("index");
                return true;
            } else
                return true;
        } else if (!JWTUtil.verifyToken(token)) {
            response.sendRedirect("login");
            return false;
        } else {
            //getRole(response,request);
            return true;
        }


    }

    /*private void getRole(HttpServletResponse response,HttpServletRequest request)  {
        String roleToken = CookieUtil.getCookieValueNamedRoleToken(request);
        if(roleToken==null||!JWTUtil.verifyToken(roleToken)){
            String token = CookieUtil.getCookieValueNamedToken(request);
            String id = JWTUtil.getClaimNamedAccount(token);
            String role = memberService.getMemberRoleByID(id);
            roleToken = JWTUtil.createRoleToken(role);
            CookieUtil.setRoleCookie(response,roleToken);
            CookieUtil.setCookie(response,"time_coo",String.valueOf(System.currentTimeMillis()),"member",-1);

        }
    }*/
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {



    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
